<?php
namespace Application\Service;

use XMLWriter;
use Zend\Config\Writer\Xml;


class XmlService extends Xml {

    public static $NUM_FIELD_NAME = "__NUM_FIELD_NAME__";
	
	public function processUserXml(array $config, $startElem)
	{
		$writer = new XMLWriter();
		$writer->openMemory();
		$writer->setIndent(true);
		$writer->setIndentString(str_repeat(' ', 4));
		
		$writer->startDocument('1.0', 'UTF-8');
		$writer->startElement($startElem);


		foreach ($config as $sectionName => $data) {
			if (!is_array($data)) {
				$writer->writeElement($sectionName, (string) $data);
			} else {
				$this->addBranch($sectionName, $data, $writer);
			}
		}
		
		$writer->endElement();
		$writer->endDocument();
		return $writer->outputMemory();
	}



    public function customXml(array $config, $startElem)
    {
        $writer = new XMLWriter();
        $writer->openMemory();
        $writer->setIndent(true);
        $writer->setIndentString(str_repeat(' ', 4));

        $writer->startDocument('1.0', 'UTF-8');
        $writer->startElement($startElem);
        $this->convertArray($config, $writer);

        $writer->endElement();
        $writer->endDocument();
        return $writer->outputMemory();
    }



    private function convertArray($config, $writer){

        $numFieldName = null;
        if(array_key_exists(XmlService::$NUM_FIELD_NAME, $config)){
            $numFieldName =  $config[XmlService::$NUM_FIELD_NAME];
            unset($config[XmlService::$NUM_FIELD_NAME]);
        }

        foreach ($config as $sectionName => $data) {
            if($numFieldName != null){
                $branchName = $numFieldName;
            } else {
                $branchName = $sectionName;
            }
            if (!is_array($data)) {
                $writer->writeElement($branchName, (string) $data);
            } else {
                $writer->startElement($branchName);
                $this->convertArray($data, $writer);
                $writer->endElement();
            }
        }
    }

	
	
	public function processUserConfig(array $string)
	{
		
		if (empty($string)) {
			return array();
		}
		$this->reader = new XMLReader();
		
		$this->reader->xml($string, null, LIBXML_XINCLUDE);
		
		$this->directory = null;
		
		set_error_handler(
		function ($error, $message = '', $file = '', $line = 0) {
			throw new Exception\RuntimeException(
					sprintf('Error reading XML string: %s', $message),
					$error
			);
		},
		E_WARNING
		);
		$return = $this->process();
		restore_error_handler();
		
		return $return;
	}
}